package com.ht.baselibs.retrofit.converter.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONReader;
import com.ht.baselibs.bean.BaseErrorBean;
import com.ht.baselibs.bean.BaseGetBean;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.ht.baselibs.utils.UIUtils;

import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {

    private Type type;


    public FastJsonResponseBodyConverter(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody responseBody) throws IOException {
        try {
            String responseStr = responseBody.string();
            String result = responseStr.substring(0, responseStr.length());
            LogUtils.debug(result);

            BaseGetBean baseGetBean = JSON.parseObject(result, BaseGetBean.class);
            BaseErrorBean baseErrorBean = JSON.parseObject(result, BaseErrorBean.class);

            if (baseGetBean.code != 0) {
                // TODO: 2017/5/2 查找原因

                if (baseGetBean.code == -1) {
                    UIUtils.showToast(baseGetBean.message);

                }
                if (baseGetBean.code == -2) {//Url超时 访问的url超时
                    SharedPreferencesUtils.put("access_Token", "");

                }
                if (baseGetBean.code == -3) {
                    UIUtils.showToast("请登录");//用户未登陆
                }

                if (baseGetBean.code == -4) {  //服务器异常
                }

                return (T) baseErrorBean;
            }


            JSONReader reader = new JSONReader(new StringReader(baseGetBean.data));
            return reader.readObject(type);
        } finally {
            responseBody.close();
        }
    }

    public interface DecodeService {
        String decode(String data);
    }

}